<template>
  <div class="notification-center">
    <el-popover placement="bottom" :width="350" trigger="click">
      <template #reference>
        <el-badge :value="unreadCount" :max="99" class="notification-badge">
          <el-button circle>
            <el-icon>
              <Bell />
            </el-icon>
          </el-button>
        </el-badge>
      </template>

      <div class="notification-header">
        <h3>通知中心</h3>
        <el-button type="text" @click="markAllAsRead" :disabled="loading || notifications.length === 0">
          清空通知
        </el-button>
      </div>

      <div class="notification-list">
        <template v-if="notifications.length > 0">
          <div v-for="notification in notifications" :key="notification.id" class="notification-item"
            :class="{ 'unread': !notification.read }" @click="markAsRead(notification)">
            <div class="notification-icon">
              <el-icon v-if="notification.type === 'overdue'" color="#E6A23C">
                <Warning />
              </el-icon>
              <el-icon v-else-if="notification.type === 'return'" color="#67C23A">
                <Check />
              </el-icon>
              <el-icon v-else-if="notification.type === 'fine'" color="#F56C6C">
                <Money />
              </el-icon>
              <el-icon v-else color="#409EFF">
                <Message />
              </el-icon>
            </div>
            <div class="notification-content">
              <div class="notification-title">{{ notification.title }}</div>
              <div class="notification-message">{{ notification.content }}</div>
              <div class="notification-time">
                {{ formatTime(notification.createTime) }}
              </div>
            </div>
          </div>
        </template>
        <div v-else class="empty-notification">
          <el-icon>
            <Document />
          </el-icon>
          <p>暂无通知</p>
        </div>
      </div>

      <div class="notification-footer">
        <div class="footer-actions">
          <el-button type="text" @click="loadMoreNotifications" :disabled="!hasMore || loading">
            加载更多
          </el-button>
          <el-button type="primary" link @click="goToNotificationCenter">
            查看全部
          </el-button>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Bell, Warning, Message, Document, Check, Money } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const notifications = ref([])
const unreadCount = ref(0)
const hasMore = ref(false)
const page = ref(1)
const size = ref(10)
const loading = ref(false)

// 加载通知
const loadNotifications = async (reset = false) => {
  if (loading.value) return

  loading.value = true

  if (reset) {
    page.value = 1
    notifications.value = []
  }

  try {
    const res = await request.get('/notifications', {
      params: {
        page: page.value - 1,
        size: size.value
      }
    })

    if (res.code === 200 && res.data) {
      if (reset) {
        notifications.value = res.data.content || []
      } else {
        notifications.value = [...notifications.value, ...(res.data.content || [])]
      }

      hasMore.value = notifications.value.length < (res.data.totalElements || 0)
      unreadCount.value = notifications.value.filter(n => !n.read).length
    }
  } catch (error) {
    console.error('加载通知失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载更多通知
const loadMoreNotifications = () => {
  page.value++
  loadNotifications()
}

// 标记通知为已读
const markAsRead = async (notification) => {
  if (notification.read) return

  try {
    await request.put(`/notifications/${notification.id}/read`)
    notification.read = true
    unreadCount.value = Math.max(0, unreadCount.value - 1)
  } catch (error) {
    console.error('标记通知已读失败:', error)
    ElMessage.error('标记通知已读失败')
  }
}

// 标记所有通知为已读
const markAllAsRead = async () => {
  if (notifications.value.length === 0 || loading.value) return

  loading.value = true

  try {
    const res = await request.put('/notifications/read-all')
    if (res.code === 200) {
      // 清空本地通知列表，因为后端已经删除了所有通知
      notifications.value = []
      unreadCount.value = 0
      hasMore.value = false
      ElMessage.success('已清空所有通知')
    } else {
      ElMessage.error('清空通知失败')
    }
  } catch (error) {
    console.error('清空通知失败:', error)
    ElMessage.error('清空通知失败')
  } finally {
    loading.value = false
  }
}

// 跳转到通知中心页面
const goToNotificationCenter = () => {
  router.push('/home/notifications')
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''

  const date = new Date(time)
  const now = new Date()

  // 如果是今天
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }

  // 如果是昨天
  const yesterday = new Date(now)
  yesterday.setDate(now.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }

  // 其他日期
  return date.toLocaleDateString('zh-CN') + ' ' +
    date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

onMounted(() => {
  // 加载通知
  loadNotifications(true)
})
</script>

<style scoped>
.notification-center {
  display: inline-block;
}

.notification-badge {
  margin-right: 16px;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
}

.notification-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.notification-list {
  max-height: 400px;
  overflow-y: auto;
  padding: 8px 0;
}

.notification-item {
  display: flex;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.notification-item:hover {
  background-color: #f5f7fa;
}

.notification-item.unread {
  background-color: #ecf5ff;
}

.notification-icon {
  margin-right: 12px;
  font-size: 20px;
}

.notification-content {
  flex: 1;
}

.notification-title {
  font-weight: 500;
  margin-bottom: 4px;
}

.notification-message {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}

.notification-footer {
  padding: 8px 16px;
  text-align: center;
  border-top: 1px solid #ebeef5;
}

.footer-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-notification {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #909399;
}

.empty-notification .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
}
</style>